package org.example.springboot_cx.Controller;

import org.example.springboot_cx.domain.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class HelloController {
    List<User> users = new ArrayList<>(){
        {
            add(new User(1,"张三"));
            add(new User(2,"李四"));
            add(new User(3,"王五"));
        }
    };


    @GetMapping("/hello")
    public String hello(){
        return "hello world";
    }

    @GetMapping("/{id}")
    public String findUser(@PathVariable int id){
        return users.stream().filter(user -> user.getId() == id) .map(User::toString)
                .findFirst()
                .orElse("User not found");
    }
    @GetMapping
    public String getUser(@RequestParam(required = false) String name, @RequestParam(defaultValue = "1") int id){
        return users.stream().filter(user -> user.getName().equals(name)).filter(user -> user.getId() == id) .map(User::toString)
                .findFirst()
                .orElse("User not found");
    }

    @PostMapping("/createUser")
    public String createUser(@RequestBody User user){
        users.add(user);
        return users.toString();
    }
    @PostMapping("/updateUser")
    public String updateUser(@RequestParam int id, @RequestParam String name){
        users.stream().filter(user -> user.getId() == id).findFirst().ifPresent(user -> user.setName(name));
        return users.toString();
    }
    @PutMapping("/{id}")
    public String updateUser(@PathVariable int id, @RequestBody User user1){
        users.stream().filter(user -> user.getId() == id).findFirst().ifPresent(user -> user.setName(user1.getName()  ));
        return users.toString();
    }
    @DeleteMapping("/{id}")
    public String updateUser(@PathVariable int id){
        users.removeIf(user -> user.getId() == id);
        return users.toString();
    }
}
